import 'package:get/get.dart';
import 'package:x_common_utils/cache_encryption_decrypt_util/cache_encryption_decrypt_util.dart';
import 'package:xinxuan/common/dialogs/del_dialog.dart';
import 'package:xinxuan/router/app_routers.dart';
import 'package:xinxuan/utils/cache_key_util.dart';
import 'package:common_utils/common_utils.dart';

class SearchPageController extends GetxController {


  String keyword = '';

  /// 搜索记录
  var searchRecord = <String>[].obs;

  @override
  void onReady() async {
    searchRecord.value = await CacheEncryptionDecryptUtil.getStringArrCacheEncryption(key: CacheKeyUtil.searchRecord);
    super.onReady();
  }

  /// 搜索，并添加搜索记录
  search(String value) async {
    keyword = value;
    List<String> _tempRecord = [];
    if (!TextUtil.isEmpty(keyword)) {
      int index = 0;
      bool keywordExist = false;
      for (int i = 0; i < searchRecord.length; i++) {
        _tempRecord.add(searchRecord[i]);
        if (searchRecord[i] == keyword) {
          keywordExist = true;
          index = i;
        }
      }
      if (keywordExist) {
        _tempRecord.removeAt(index);
      }
      _tempRecord.insert(0, keyword);
      searchRecord.value = _tempRecord;
      await CacheEncryptionDecryptUtil.saveStringArrCacheEncryption(key: CacheKeyUtil.searchRecord, value: searchRecord);
    }
    Get.offAndToNamed(
      '${AppRouters.COMMON_PAGE}${AppRouters.SEARCH_PAGE}${AppRouters.SEARCH_RECORD_PAGE}',
      arguments: {
        'keyword': keyword
      }
    );
  }

  /// 清除搜索记录
  cleanSearchRecord() async {
    Get.dialog(
      DelDialog(message: '确定清空搜索历史吗？', onTap: () async {
        searchRecord.value = [];
        await CacheEncryptionDecryptUtil.removeByKey(key: CacheKeyUtil.searchRecord);
      })
    );
  }

}